from django.contrib.syndication.feeds import Feed
from django.core.cache import cache
from django.conf import settings
from blogs.models import Blog, Post
from blogs.utils import get_cached_object

class LatestPosts(Feed):
    title = "jam.slicio.us news"
    link = "http://jam.slicio.us/"
    description = "Updates on changes and additions to jam.slicio.us."
    
    def get_object(self, bits):
        if len(bits) == 1:
            return get_cached_object('Blog:%s' % bits[0], Blog, pk=bits[0])
        elif len(bits) == 0:
            return None
        else:
            raise ObjectDoesNotExist

    def title(self, obj):
        if not obj:
            return 'jam.slicio.us'
        return 'jam.slicio.us: %s' % obj.name

    def link(self, obj):
        if not obj:
            return 'http://jam.slicio.us/'
        return obj.get_absolute_url()

    def description(self, obj):
        if not obj:
            return 'Latest posts from jam.slicio.us'
        return 'Latest posts from jam.slicio.us: %s' % obj.name
        
    def items(self, obj):
        posts = []
        
        if (obj):
            cache_key = 'Blog:%s_posts' % obj.slug
            
            posts = cache.get(cache_key)
            
            if posts == None:
                posts = obj.get_posts()
                cache.set(cache_key, list(posts), settings.DEFAULT_CACHE_TIME)
        else:
            cache_key = 'latest_posts'
            
            posts = cache.get(cache_key)
            
            if posts == None:
                posts = Post.objects.filter(pub_date__isnull=False).order_by('-pub_date')[:10]
                cache.set(cache_key, posts, settings.DEFAULT_CACHE_TIME)
        
        return posts[:10]
